using System;
using System.Collections;
using System.Collections.Generic;
using QFramework;
using UnityEngine;
using UnityEngine.UI;

//TODO 改为直接显示红色对勾
public class ShowRightAnswer : MonoBehaviour
{
    // Start is called before the first frame update
    public GameObject[] rightAnswerPanel;
    private int rightAnswerIndex = 0;
    public Text daoJiShiText;
    private int daoJiShi = 5;
    private Coroutine countdownCoroutine;

    void Start()
    {
        StringEventSystem.Global.Register(EventID.ShowRightAnswer, (CorrectAnswerStructure correctAnswerStructure) =>
        {
            ShowRightAnswerFun(correctAnswerStructure);
        }
        ).UnRegisterWhenGameObjectDestroyed(gameObject);
    }

    // Update is called once per frame
    private void ShowRightAnswerFun(CorrectAnswerStructure correctAnswerStructure)
    {
        rightAnswerIndex = correctAnswerStructure.rightAnswer;
        if (rightAnswerIndex > 0){
            rightAnswerPanel[rightAnswerIndex-1].SetActive(true);
        }
        // zhengQueLveText.text = "本题正确率："+correctAnswerStructure.zhengQueLveText;
        startDaoJiShi();
        
    }

    private void startDaoJiShi()
    {
        // 如果已经有倒计时在运行，先停止它
        if (countdownCoroutine != null)
        {
            StopCoroutine(countdownCoroutine);
        }
        
        daoJiShiText.text = "5s";
        countdownCoroutine = StartCoroutine(DaoJiShi());
    }

    //设计一个倒计时的协程
    IEnumerator DaoJiShi()
    {
        int remainingTime = daoJiShi;
        while (remainingTime > 0)
        {
            if (!TimeStop.isTimeStop)
            {
                yield return new WaitForSeconds(1);
                remainingTime--;
                daoJiShiText.text = remainingTime.ToString() + "s";
            }
            else
            {
                yield return null; // 暂停时等待一帧
            }
        }
        
        rightAnswerPanel[rightAnswerIndex-1].SetActive(false);
         //然后发出下一题的事件
        StringEventSystem.Global.Send(EventID.NextTi);
        StringEventSystem.Global.Send(EventID.HideAnswer);
        countdownCoroutine = null;
    }

    void OnDestroy()
    {
        if (countdownCoroutine != null)
        {
            StopCoroutine(countdownCoroutine);
        }
    }
}
